import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

public class UDPClient {

    private static int port = 16661;

    private static class CLientHandler extends SimpleChannelInboundHandler<DatagramPacket> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {

        }
    }

    public static void main(String[] args) throws Exception {

        BufferedReader reader = new BufferedReader(new FileReader(
                new File("D:\\config\\raw-8.log")));


        List<String> data = new ArrayList<String>();
        String s;
        while ((s=reader.readLine())!=null){
            data.add(s);
        }
        Long ft = Long.parseLong(data.get(0).split(":")[0]);
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    .handler(new CLientHandler());

            Channel ch = b.bind(0).sync().channel();
            System.out.println("start....");
            for (String line:data){
                Long t = Long.parseLong(line.split(":")[0]);
                String raw = line.split(":")[1];

                ch.writeAndFlush(new DatagramPacket(
                        Unpooled.copiedBuffer(ByteBufUtil.decodeHexDump(raw)),
                        new InetSocketAddress("127.0.0.1", port))).sync();

                Thread.sleep(t-ft);
                ft = t;

            }

//            ch.closeFuture().await();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
            reader.close();
        }


        System.out.println("end.....");
    }

}
